package com.zbkj.admin.boot.common.error;

import cn.hutool.core.util.StrUtil;
import jakarta.validation.ConstraintViolation;
import net.dreamlu.mica.core.result.R;
import net.dreamlu.mica.core.result.SystemCode;
import org.hibernate.validator.internal.engine.path.PathImpl;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.Set;

/**
 * 抽取共性 通用部分代码
 *
 * @author L.cm
 */
public abstract class BaseExceptionTranslator {

    /**
     * 处理 BindingResult
     *
     * @param result BindingResult
     * @return R
     */
    protected R<Object> handleError(BindingResult result) {
        FieldError error = result.getFieldError();
        String message = String.format("%s:%s", error.getField(), error.getDefaultMessage());
        return R.fail(SystemCode.PARAM_BIND_ERROR, message);
    }

    /**
     * 处理 ConstraintViolation
     *
     * @param violations 校验结果
     * @return R
     */
    protected R<Object> handleError(Set<ConstraintViolation<?>> violations) {
        ConstraintViolation<?> violation = violations.iterator().next();
        String path = ((PathImpl) violation.getPropertyPath()).getLeafNode().getName().replaceAll("arg0", "");
        String message = String.format("%s%s%s", path, StrUtil.isNotBlank(path) ? ":" : "", violation.getMessage());
        return R.fail(SystemCode.PARAM_VALID_ERROR, message);
    }
}
